import {
  AddAppAuthParams,
  AliaItem,
  AppAuthTableItem,
  AppAuthTableParams,
  AppItem,
  EditAppAuthParams,
  PackageItem,
} from './model/enterpriseAppAuthModel';
import { tenantHttp } from '/@/utils/http/axios';
import dayjs from 'dayjs';

enum Api {
  GET_APP_AUTH_TABLE = '/appAuthorization/tenantAppAuthorizations',
  ADD_AUTH = '/appAuthorization/createTenantAppAuth',
  GET_PACKAGE_LIST = '/appAuthorization/packagesByAppId',
  EDIT = '/appAuthorization/updateTenantAppAuth',
  DELETE = '/appAuthorization/deleteTenantAppAuth',
  GET_CHINESE_NAME = '/appAuthorization/getTenantIdAlias',
  GET_APP_LIST = '/appAuthorization/getBusinessApps',
}

export const getAppAuthTable = async (params: AppAuthTableParams) => {
  const res = await tenantHttp.post<AppAuthTableItem>({
    url: Api.GET_APP_AUTH_TABLE,
    params,
  });
  res.items.map((item) => {
    if (item.expireTime !== '--') {
      item.expireTime = dayjs(item.expireTime).format('YYYY-MM-DD HH:mm:ss');
    }
    return item;
  });
  return res;
};

export const addAppAuth = async (params: AddAppAuthParams) => {
  const res = await tenantHttp.post<string>({
    url: Api.ADD_AUTH,
    params,
  });
  return res;
};

export const editAppAuth = async (params: EditAppAuthParams) => {
  const res = await tenantHttp.get<string>({
    url: Api.EDIT,
    params,
  });
  return res;
};

export const getPackagesOpt = async (app: number) => {
  const params = { appId: app };
  const res = await tenantHttp.get<PackageItem[]>({
    url: Api.GET_PACKAGE_LIST,
    params,
  });
  const result = res.map((item) => {
    return {
      label: item.packageType,
      value: item.packageId,
    };
  });
  return result;
};

export const deleteAppAuth = async (params: number) => {
  const res = await tenantHttp.delete<string>({
    url: Api.DELETE + '?id=' + params,
  });
  return res;
};

export const getAlias = async () => {
  const res = await tenantHttp.get<AliaItem[]>({
    url: Api.GET_CHINESE_NAME,
  });
  const result = res.map((item) => {
    return {
      label: item.tenantAlias,
      value: item.tenantId,
    };
  });
  return result;
};

export const getBusinessAppOpt = async () => {
  const res = await tenantHttp.get<AppItem[]>({
    url: Api.GET_APP_LIST,
  });
  const result = res.map((item) => {
    return { label: item.appName, value: item.appId };
  });
  return result;
};
